package com.augrain.microframework.web;

import com.augrain.microframework.core.consts.StrConst;
import com.augrain.microframework.core.util.StringUtils;
import com.augrain.microframework.web.base.ApiContext;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * 构建ApiContext对象，放入线程变量
 *
 * @author biaoy
 * @since 2020/11/26
 */
@Slf4j
@Order(0)
public class ApiParamRequestFilter extends OncePerRequestFilter {

    /**
     * 过滤器方法，创建ApiContext
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse httpServletResponse,
                                    FilterChain filterChain) throws ServletException, IOException {
        String api = request.getRequestURI();

        ApiContext.ApiContextBuilder builder = ApiContext.builder();
        builder.api(api).request(request).response(httpServletResponse);

        ApiContext apiContext = builder
                .cid(request.getParameter("cid"))
                .gid(request.getParameter("gid"))
                .ctype(request.getParameter("ctype"))
                .build();

        StringBuilder logKey = new StringBuilder("[ApiLog][").append(api).append("][").append(apiContext.getSid());
        if (!StringUtils.isEmpty(apiContext.getGid())) {
            logKey.append("[g:").append(apiContext.getGid()).append(StrConst.STR_RIGHT_SQUARE_BRACKETS);
        } else {
            logKey.append("[c:").append(StringUtils.nullToEmpty(apiContext.getCtype()))
                    .append(StringUtils.nullToEmpty(apiContext.getCid())).append(StrConst.STR_RIGHT_SQUARE_BRACKETS);
        }
        apiContext.setLogKey(logKey.toString());
        ApiContext.current.set(apiContext);

        if (log.isDebugEnabled()) {
            logger.debug("[API][REQ][" + apiContext.getClientIP() + ":" + apiContext.getClientPort()
                    + StrConst.STR_RIGHT_SQUARE_BRACKETS + request.getParameter("params"));
        }

        // 保存apilog到MDC中
        MDC.put("apilog", logKey.toString());
        filterChain.doFilter(request, httpServletResponse);
    }

}
